package login

import (
	"github.com/gin-gonic/gin"
	menudao "go-small-shopping/dao/menu"
	"go-small-shopping/dao/user"
	"go-small-shopping/db"
	login_req "go-small-shopping/entity/dto"
	"go-small-shopping/entity/menu"
	"go-small-shopping/entity/rs"
	entityuser "go-small-shopping/entity/user"
	"go-small-shopping/jwt"
	"go-small-shopping/service"
)

func Login(name string, password string) (*entityuser.UserInfo, error) {
	params := &entityuser.UserInfo{Name: name, Password: password}
	return userdao.FindUserById(params)
}

func Login2(g *gin.Context) {
	loginUser := &login_req.LoginUser{}
	js := &rs.Json{}

	err := g.ShouldBindBodyWithJSON(loginUser)
	if err != nil {
		js = rs.Fail("参数错误")
		g.JSON(200, js)
		return
	}
	query := &entityuser.UserInfo{Name: loginUser.Username, Password: loginUser.Password}
	dbUser := userdao.FindUserByEntity(query)
	if dbUser == nil {
		js = rs.FailCustomCode(400, "用户名或密码错误")
	} else {
		//获取菜单
		loginUser.Menus = menudao.CollapsibleAllMenus()
		token, err := jwt.GenerateJWT(loginUser)
		if err != nil {
			js = rs.Fail("生成token失败")
		} else {
			js = rs.Ok(token)
		}
	}
	g.JSON(200, js)
}

func GetUserInfo(g *gin.Context) {
	token := g.GetHeader("token")
	loginUser, err := jwt.ParseToken(token)

	var js *rs.Json
	if err != nil {
		js = rs.Fail("parse token error")
	} else {
		js = rs.Ok(loginUser)
	}
	g.JSON(200, js)
}

func GetUserInfoFromToken(g *gin.Context) {
	token := g.GetHeader("token")
	jwt.ValidateJWT(token)

	loginUser := cahce_user_service.GetUser(token)
	js := &rs.Json{
		Code: 200,
		Data: loginUser,
		Msg:  "success",
	}
	g.JSON(200, js)
}

func Menu(g *gin.Context) {
	var menus []*menu.Menu
	db.GetBbCon().Find(&menus)
	js := rs.Ok(menus)

	g.JSON(200, js)
}
